<template>
  <div v-if="!hasPermission('role:manage')" style="text-align: center; padding: 50px;">
    <a-result
      status="403"
      title="403"
      sub-title="抱歉，您没有权限访问角色权限管理页面。"
    >
      <template #extra>
        <a-button type="primary" @click="goToHome">返回首页</a-button>
      </template>
    </a-result>
  </div>
  
  <div v-else>
    <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
      <div></div>
      <a-button 
        v-if="hasPermission('role:manage')" 
        type="primary" 
        @click="showModal"
      >
        分配权限
      </a-button>
    </div>

    <a-modal v-model:open="open" title="分配权限" @ok="handleAssignPermission" @cancel="resetForm">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="选择角色" name="roleId">
          <a-select
            v-model:value="formState.roleId"
            placeholder="请选择角色"
            show-search
            :filter-option="filterRoleOption"
          >
            <a-select-option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.roleName }} ({{ role.roleCode }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择权限" name="permissionIds">
          <a-select
            v-model:value="formState.permissionIds"
            placeholder="请选择权限"
            mode="multiple"
            show-search
            :filter-option="filterPermissionOption"
          >
            <a-select-option v-for="permission in permissions" :key="permission.id" :value="permission.id">
              {{ permission.permissionName }} ({{ permission.permissionCode }})
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-table 
      bordered
      :data-source="dataSource"
      :columns="columns"
      :loading="loading"
      :pagination="false"
      row-key="id"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'roleName' || column.dataIndex === 'roleCode'">
          <div>
            <span>{{ text }}</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'permissions'">
          <div>
            <template v-if="record.id === 1">
              <a-tag color="purple">所有权限</a-tag>
            </template>
            <template v-else-if="record.id === 2">
              <a-tag color="blue">增删改查权限</a-tag>
            </template>
            <template v-else>
              <a-tag v-for="permission in record.permissions" :key="permission.id" color="green" style="margin: 2px">
                {{ permission.permissionName }}
              </a-tag>
              <span v-if="!record.permissions || record.permissions.length === 0">暂无权限</span>
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createdAt'">
          {{ formatDate(text) }}
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a-button 
              v-if="hasPermission('role:manage')" 
              type="link" 
              size="small" 
              @click="showEditModal(record)"
              style="margin-right: 8px"
            >
              编辑权限
            </a-button>
            <a-popconfirm
              v-if="hasPermission('role:manage') && dataSource.length"
              title="确定要删除该角色的所有权限吗？"
              @confirm="onDeleteRolePermissions(record.id)"
            >
              <a-button type="link" size="small" danger>删除权限</a-button>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>
    
    <div style="margin-top: 16px; text-align: right;">
      <a-pagination 
        v-model:current="current"
        show-quick-jumper
        :page-size-options="['5', '10', '20']"
        :total="total"
        @change="onChange"
        :page-size="pageSize"
        show-size-changer
      />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import request from '@/utils/request'
import PermissionUtil from '@/utils/permission'

// 权限检查
const hasPermission = (permission) => PermissionUtil.hasPermission(permission)

const originalDataSource = ref([])

// 分页
const current = ref(1)
const total = ref(0)
const pageSize = ref(10)
const loading = ref(false)

// 表单配置
const formRef = ref()
const labelCol = { span: 6 }
const wrapperCol = { span: 16 }
const open = ref(false)

const formState = reactive({
  roleId: undefined,
  permissionIds: []
})

const rules = {
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  permissionIds: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
}

const roles = ref([])
const permissions = ref([])
const currentRole = ref(null)

const columns = [
  {
    title: '角色ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '角色名称',
    dataIndex: 'roleName'
  },
  {
    title: '角色编码',
    dataIndex: 'roleCode'
  },
  {
    title: '权限',
    dataIndex: 'permissions',
    width: 300
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 200
  }
]

const dataSource = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 初始化数据
const initData = async () => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有查询权限')
    return
  }
  
  loading.value = true
  try {
    const response = await request.get(`/roles/permissions`, { params: { page: current.value, size: pageSize.value } })
    if (response.data.success) {
      originalDataSource.value = response.data.data
      dataSource.value = response.data.data
      total.value = response.data.total || response.data.data.length
    } else {
      message.error('获取角色权限列表失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '获取角色权限列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化角色和权限数据
const initRolesAndPermissions = async () => {
  try {
    const [rolesResponse, permissionsResponse] = await Promise.all([
      request.get('/roles'),
      request.get('/permissions')
    ])
    
    if (rolesResponse.data.success) {
      roles.value = rolesResponse.data.data
    }
    if (permissionsResponse.data.success) {
      permissions.value = permissionsResponse.data.data
    }
  } catch (error) {
    message.error('初始化数据失败')
  }
}


// 分页
const onChange = (page, pageSize) => {
  current.value = page
  pageSize.value = pageSize
  initData()
}

// 筛选选项
const filterRoleOption = (input, option) => {
  const text = option.children[0].children
  return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const filterPermissionOption = (input, option) => {
  const text = option.children[0].children
  return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 模态框
const showModal = () => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有分配权限权限')
    return
  }
  currentRole.value = null
  formState.roleId = undefined
  formState.permissionIds = []
  open.value = true
  initRolesAndPermissions()
}

const showEditModal = (record) => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有编辑权限权限')
    return
  }
  currentRole.value = record
  formState.roleId = record.id
  formState.permissionIds = record.permissions ? record.permissions.map(permission => permission.id) : []
  open.value = true
  initRolesAndPermissions()
}

const resetForm = () => {
  formRef.value?.resetFields()
  currentRole.value = null
}

const handleAssignPermission = () => {
  formRef.value?.validate().then(async () => {
    try {
      const assignData = {
        roleId: formState.roleId,
        permissionIds: formState.permissionIds
      }
      
      const response = await request.post('/roles/permissions', assignData)
      if (response.data.success) {
        message.success('权限分配成功')
        open.value = false
        resetForm()
        initData()
      } else {
        message.error(response.data.message || '分配失败')
      }
    } catch (error) {
      message.error(error.response?.data?.message || '分配失败')
    }
  }).catch(() => {
    message.error('请检查表单输入')
  })
}

// 删除角色权限
const onDeleteRolePermissions = async (roleId) => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有删除权限权限')
    return
  }
  
  try {
    const response = await request.delete(`/roles/${roleId}/permissions`)
    if (response.data.success) {
      message.success('角色权限删除成功')
      initData()
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '删除失败')
  }
}

const goToHome = () => {
  window.location.href = '/hotel/users'
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  margin-top: 4px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>